package com.bit.silverstar;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public abstract class ArcadeGame extends LinearLayout{
	private Context mContext;
	private Timer mUpdateTimer;
	private long mPeriod = 1000;
	
	abstract protected void initialize();
	
	abstract protected boolean gameOver();
	
	abstract protected long getScore();
	
	abstract protected void updatePhysics();
	
	abstract protected void soundStop();
	
	public ArcadeGame(Context context) {
		super(context);
		mContext = context;
	}
	public ArcadeGame(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
	}
	public void viewStop(){

		//mContext.startActivity(new Intent(mContext,LoadingActivity.class));
		Intent i = new Intent(mContext,SetActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(i);
		stopUpdateTimer();

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		super.onLayout(changed, l, t, r, b);
		try {
			initialize();
			startUpdateTimer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void setUpdatePeriod(long period) {
		mPeriod = period;
		
	}
	protected Bitmap getImage(int id) {
		return BitmapFactory.decodeResource(mContext.getResources(), id);
	}
	protected Bitmap ImageSize(Bitmap bit,int width, int height) {
		return Bitmap.createScaledBitmap(bit, width, height, true);
	}
	
	protected void startUpdateTimer() {
		mUpdateTimer = new Timer();
		mUpdateTimer.schedule(new UpdateTask(), 0, mPeriod);
	}
	
	protected void stopUpdateTimer() {
		if (mUpdateTimer != null) {
			mUpdateTimer.cancel();
			soundStop();
		}
	}
	private class UpdateTask extends TimerTask{

		@Override
		public void run() {
			updatePhysics();
			
			try{
			postInvalidate();
			}catch (Exception e){
				e.printStackTrace();
			}
		}
	}
	public void halt() {
		stopUpdateTimer();
	}
	
	protected AudioClip getAudioClip(int id) {
		return new AudioClip(mContext, id);
	}
	
}
